import utils from "@/utils";
import Request from './Request';
import { URL_BASE_GETDATA } from './../config';

/**
 * 反escape解密对象中所有值
 * @param {Object} obj
 * @return {Object}
 */
 const unescapeJSON = obj => {
    if (typeof obj === 'object' && obj != null) {
      for (let i in obj) {
        obj[i] = unescapeJSON(obj[i]);
      }
      return obj;
    } else if (typeof obj === 'string') {
      return unescape(obj.replace(/%22/g, '%2522'));
    } else {
      return obj;
    }
  };

export default class HbbRequest extends Request {
    _errorCodeRules = {};
    ownCallback = false;
    constructor(hbbApi, data = {}, { ownCallback = false } = {}) {
      super({
        url: URL_BASE_GETDATA,
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' }
      });
    //   let APIEntID = state.APIEntID ? state.APIEntID : '';
      this.data = {
        HBBWSType: hbbApi.getServerType(),
        strKeyName: hbbApi.getKeyName(),
        strJsonData: JSON.stringify(data),
        strAuthorizationCode: 'hbb',
        IsRSA: 0,
        // APIEntID
      };
      this.ownCallback = ownCallback;
    }
  
    addErrorCodeRule(code, handler) {
      this._errorCodeRules[code] = handler;
      return this;
    }
  
    removeAllErrorCodeRule() {
      this._errorCodeRules = {};
      return this;
    }
  
    send() {
      return utils
        .promisify(uni.request)({
          url: this.url,
          data: this.data,
          method: this.method,
          header: this.header
        })
        .catch(err => {
          console.log(err);
          return utils.fail('网络连接异常').then(() => Promise.reject());
        })
        .then(({ data }) => {
          let rs = unescapeJSON(data);
  
          if (this.ownCallback) {
            return Promise.resolve(rs);
          }
  
          const errCodeRulesKeys = Object.keys(this._errorCodeRules);
  
          if (
            rs.errcode &&
            rs.errcode == '0' &&
            rs.resultcode &&
            rs.resultcode == '0'
          ) {
            return Promise.resolve(rs);
          } else if (
            errCodeRulesKeys.length > 0 &&
            ((rs.errcode && errCodeRulesKeys.includes(rs.errcode)) ||
              (rs.resultcode && errCodeRulesKeys.includes(rs.resultcode)))
          ) {
            const _code = rs.resultcode == '0' ? rs.errcode : rs.resultcode;
            return this._errorCodeRules[_code](rs);
          } else {
            const msg = rs.errmsg || rs.resultmsg || JSON.stringify(rs);
            return utils.fail(msg).then(() => Promise.reject(rs));
          }
        });
    }
  }